
<template>
	<view class="container" :style="{ '--theme-color': themeColor }">
		<!-- 标题栏 -->
		<title-bar :showBack="true" title="订单确认"></title-bar>
		<!-- 内容区 -->
		<view class="container-main" v-if="loadEnd">
			<!-- 发货方式 -->
			<view class="main-method flex align-items-center" @click="openDeliveryMethod" v-if="mallConfig.self_pickup_status == 1">
				<view class="method-title">发货方式</view>
				<view class="method-value flex-item">{{deliveryMethod == 2 ? "到店自提" : "快递发货"}}</view>
				<image class="method-icon" src="/static/right.png" mode="aspectFit"></image>
			</view>
			<!-- 到店自提 -->
			<view class="main-address" v-if="deliveryMethod == 2">
				<view class="address-title">自提地址</view>
				<view class="address-box flex align-items-center" @click="toNavigation()">
					<view class="box-text flex-item">{{mallConfig.address}}</view>
					<view class="box-icon" :style="{'background-image': 'url('+ iconMore +')'}" v-if="iconMore"></view>
				</view>
				<view class="address-info flex flex-wrap" v-if="mallConfig.mobile" @click="onContact()">{{mallConfig.mobile}}</view>
			</view>
			<!-- 地址选择 -->
			<view class="main-address" @click="chooseAddress()" v-else>
				<view class="address-box flex align-items-center">
					<view class="box-text flex-item">{{addressData.address || "请选择收货地址"}}</view>
					<view class="box-icon" :style="{'background-image': 'url('+ iconMore +')'}" v-if="iconMore"></view>
				</view>
				<view class="address-info flex flex-wrap" v-if="addressData.name && addressData.tel">
					<text>{{addressData.name || ""}}</text>
					<text>{{addressData.tel || ""}}</text>
				</view>
			</view>
			<!-- 商品信息 -->
			<view class="main-goods">
				<block v-for="(item, index) in goodsData" :key="index">
					<mall-store :show-data="item" :show-number="item.number" @changeNumber="changeNumber($event, index)"></mall-store>
				</block>
			</view>
			<!-- 商品费用 -->
			<view class="main-cost">
				<view class="cost-info">
					<view class="title">商品总额</view>
					<view class="value">￥{{totalPrice}}</view>
				</view>
				<view class="cost-info" v-if="deliveryMethod == 1">
					<view class="title">运费总额</view>
					<view class="value">￥{{parseFloat(orderFreight).toFixed(2)}}</view>
				</view>
			</view>
			<!-- 底部按钮 -->
			<view class="main-footer">
				<view class="flex align-items-center">
					<view class="footer-money text-ellipsis-more"><text>￥</text>{{getOrderAmount()}}</view>
					<view class="footer-btn flex-item" @click="submitOrder()" v-if="userMobile">提交订单</view>
					<button class="footer-btn flex-item clear" open-type="getPhoneNumber" @getphonenumber="bindPhoneNumber" v-else>提交订单</button>
				</view>
				<view class="safe-padding"></view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				// 页面是否阻止滚动
				pageShow: false,
				// 是否加载完成
				loadEnd: true,
				// 商品数据
				goodsData: [],
				// 发货方式
				deliveryMethod: 1,
				// 已选地址
				addressData: {},
				// 订单运费
				orderFreight: 0,
				// 是否为购物车商品
				isCartItem: false,
				// 商城配置
				mallConfig: {},
			};
		},
		
		methods: {
			// 改变页面滚动状态
			pageChange(state) {
				this.pageShow = state
			},
			// 获取商品详情
			getGoodsDetails(fn) {
				if (this.$store.state.app.mallOrder && this.$store.state.app.mallOrder.list && this.$store.state.app.mallOrder.list.length) {
					this.goodsData = this.$store.state.app.mallOrder.list || []
					this.isCartItem = this.$store.state.app.mallOrder.isCartItem || false
					this.getAddress(() => {
						this.getPostage(fn)
					})
				} else {
					uni.hideLoading()
					uni.showModal({
						title: "提示",
						content: "请选择商品后下单",
						showCancel: false,
						confirmText: "返回",
						confirmColor: this.themeColor,
						complete: () => {
							uni.navigateBack()
						}
					})
				}
			},
			// 获取商城配置
			getMallConfig() {
				this.$util.request("mall.config").then(res => {
					if (res.code == 1) {
						this.mallConfig = res.data
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
					}
				}).catch(error => {
					console.error('获取商城配置', error)
				})
			},
			// 获取默认地址
			getAddress(fn) {
				this.$util.request("mall.addressList", {
					is_default: 1
				}).then(res => {
					if (res.code == 1) {
						if (res.data[0]) this.addressData = res.data[0]
						if (fn) fn()
					} else {
						if (fn) fn()
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
					}
				}).catch(error => {
					if (fn) fn()
					console.error('获取默认地址', error)
				})
			},
			// 获取运费
			getPostage(fn) {
				if (this.deliveryMethod == 2) {
					if (fn) fn()
					return
				}
				if (!this.addressData || !this.addressData.id) {
					if (fn) fn()
					return
				}
				this.$util.request("mall.getPostage", {
					pay_price: this.totalPrice,
					address_id: this.addressData.id
				}).then(res => {
					if (fn) fn()
					if (res.code == 1) {
						this.orderFreight = parseFloat(res.data.price)
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
					}
				}).catch(error => {
					if (fn) fn()
					console.error('获取运费', error)
				})
			},
			// 绑定手机号
			bindPhoneNumber(e) {
				if (e.detail.errMsg == "getPhoneNumber:ok") {
					uni.showLoading({
						mask: true,
						title: "加载中",
					})
					uni.login({
						provider: 'weixin',
						success: loginRes => {
							let data = e.detail
							data.code = loginRes.code
							this.$util.request("login.bindMobile", data).then(res => {
								uni.hideLoading()
								if (res.code == 1) {
									this.$store.commit('user/updateMobile', res.data.phoneNumber)
									this.submitOrder()
								} else {
									uni.showToast({
										title: res.msg,
										icon: 'none'
									})
								}
							}).catch(error => {
								uni.hideLoading()
								console.error('获取用户手机号码 ', error)
							})
						},
						fail: () => {
							uni.hideLoading()
							uni.showToast({
								icon: "none",
								title: "授权手机号失败，请重试"
							})
						}
					});
				} else {
					uni.showToast({
						title: '获取手机号失败，请重新获取',
						icon: 'none'
					})
				}
			},
			// 打开发货方式弹窗
			openDeliveryMethod() {
				const methodList = [
					{ id: 1, name: "快递发货" },
					{ id: 2, name: "到店自提" },
				]
				this.$refs.selectPicker.open(methodList, this.deliveryMethod)
			},
			// 改变发货方式
			changeDeliveryMethod(value) {
				this.deliveryMethod = value.id
				if (value.id == 1) {
					uni.showLoading({
						title: "加载中",
						mask: true
					})
					this.getPostage(() => {
						uni.hideLoading()
					})
				}
			},
			// 选择地址
			chooseAddress() {
				this.$refs.addressModal.open(this.addressData.id)
			},
			// 改变选择的地址
			changeAddress(item) {
				this.addressData = item
				this.getPostage()
			},
			// 跳转地图导航
			toNavigation() {
				this.$util.toPage({
					mode: 7,
					address: {
						latitude: this.mallConfig.latitude,
						longitude: this.mallConfig.longitude,
						address: this.mallConfig.address,
					},
				})
			},
			// 联系
			onContact() {
				this.$util.toPage({
					mode: 6,
					phone: this.mallConfig.mobile,
				})
			},
			// 改变商品数量
			changeNumber(type, index) {
				if (type == 1) {
					if (parseInt(this.goodsData[index].number) > 1) {
						const goodsNumber = parseInt(this.goodsData[index].number) - 1
						this.changeQuantity(goodsNumber, index)
					}
				} else if (type == 2) {
					const goodsNumber = parseInt(this.goodsData[index].number) + 1
					this.changeQuantity(goodsNumber, index)
				} else if (type == 3) {
					this.$refs.quantityModal.open(this.goodsData[index].number, index)
				}
			},
			// 选择商品数量
			changeQuantity(number, index) {
				uni.showLoading({
					mask: true,
					title: "加载中"
				})
				if (this.isCartItem) {
					this.$util.request("mall.updateCartNumber", {
						goods_id: this.goodsData[index].id,
						number: number,
					}).then(res => {
						if (res.code == 1) {
							this.$set(this.goodsData[index], "number", parseInt(number))
							this.getPostage(() => {
								uni.hideLoading()
							})
						} else {
							uni.hideLoading()
							uni.showToast({
								title: res.msg,
								icon: 'none'
							})
						}
					}).catch(error => {
						uni.hideLoading()
						console.error('更新购物车商品数量', error)
					})
				} else {
					this.$set(this.goodsData[index], "number", parseInt(number))
					this.getPostage(() => {
						uni.hideLoading()
					})
				}
			},
			// 获取订单总额
			getOrderAmount() {
				var result = 0
				if (this.deliveryMethod == 2) result = parseFloat(this.totalPrice)
				else result = parseFloat(this.totalPrice) + parseFloat(this.orderFreight)
				return parseFloat(result).toFixed(2)
			},
			// 提交订单
			submitOrder() {
				if (!this.addressData || !this.addressData.id) {
					uni.showToast({
						title: "请选择收货地址",
						icon: "none"
					})
					return;
				}
				uni.showLoading({
					title: "提交中",
					mask: true
				})
				var data = {
					goods_id: this.goodsData.map(item => item.id).join(),
					buy_now: this.isCartItem ? 2 : 1,
					delivery_method: this.deliveryMethod,
				}
				if (!this.isCartItem) data.number = this.goodsData[0].number
				if (this.deliveryMethod == 1) data.address_id = this.addressData.id
				this.$util.request("mall.createOrder", data).then(res => {
					uni.hideLoading()
					if (res.code == 1) {
						this.$util.toPage({
							mode: 2,
							path: `/pagesMall/order/payment?money=${this.getOrderAmount()}&id=${res.data.order_id}`
						})
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
					}
				}).catch(error => {
					console.error('创建订单', error)
				})
			},
		}
	}
</script>

<style lang="scss">
	.container {
		page {
			background: #F6F7FB;
			padding-bottom: constant(safe-area-inset-bottom);
			padding-bottom: env(safe-area-inset-bottom);
		}
		
		image {
			display: block;
			width: 100%;
			height: 100%;
		}
		
		view {
			box-sizing: border-box;
		}
		
		button::after {
			border: none;
		}
		
		button.clear {
			padding: 0;
			margin: 0;
			border: none;
			background: transparent;
			line-height: 1.3;
		}
		
		button.clear::after {
			display: none;
		}
		
		.alignment {
			display: flex;
			justify-content: center;
			align-items: center;
			text-align: center;
		}
		
		.alignments {
			display: flex;
			align-items: center;
		}
		page {
			padding-bottom: 0;
		}
		
		.flex {
			display: flex;
		}
		
		.inline-flex {
			display: inline-flex;
		}
		
		.flex-item {
			flex: 1;
			min-width: 0;
		}
		
		.flex-center {
			align-items: center;
			justify-content: center;
		}
		
		.flex-wrap {
			flex-wrap: wrap;
		}
		
		.flex-direction-column {
			display: flex;
			flex-direction: column;
		}
		
		.align-items-center {
			align-items: center;
		}
		
		.align-items-start {
			align-items: flex-start;
		}
		
		.align-items-end {
			align-items: flex-end;
		}
		
		.justify-content-between {
			justify-content: space-between;
		}
		
		.justify-content-around {
			justify-content: space-around;
		}
		
		.justify-content-center {
			justify-content: center;
		}
		
		.justify-content-start {
			justify-content: flex-start;
		}
		
		.justify-content-end {
			justify-content: flex-end;
		}
		
		.wbcentre {
			text-align: center;
		}
		
		.text-ellipsis {
			white-space: nowrap;
			overflow: hidden;
			text-overflow: ellipsis;
			word-break: break-all;
		}
		
		.text-ellipsis-more {
			display: -webkit-box;
			-webkit-box-orient: vertical;
			overflow: hidden;
			-webkit-line-clamp: 2;
			word-break: break-all;
		}
		
		.safe-padding {
			width: 100%;
			padding-bottom: constant(safe-area-inset-bottom);
			padding-bottom: env(safe-area-inset-bottom);
		}
		.container-main {
			padding: 32rpx 32rpx 144rpx;

			.main-method {
				border-radius: 20rpx;
				padding: 32rpx;
				background: #FFF;
				margin-bottom: 32rpx;

				.method-title {
					color: #5A5B6E;
					font-size: 28rpx;
					font-weight: 600;
					line-height: 40rpx;
				}

				.method-value {
					margin-left: 24rpx;
					color: #5A5B6E;
					font-size: 28rpx;
					line-height: 40rpx;
					text-align: right;
				}

				.method-icon {
					margin-left: 16rpx;
					width: 32rpx;
					height: 32rpx;
				}
			}

			.main-address {
				border-radius: 20rpx;
				padding: 32rpx;
				background: #FFF;

				.address-title {
					color: #5A5B6E;
					font-size: 28rpx;
					font-weight: 600;
					line-height: 40rpx;
					margin-bottom: 24rpx;
				}

				.address-box {
					.box-text {
						color: #5A5B6E;
						font-size: 32rpx;
						line-height: 44rpx;
						margin-right: 64rpx;
					}

					.box-icon {
						width: 32rpx;
						height: 32rpx;
						background-size: 32rpx;
					}
				}

				.address-info {
					margin-top: 24rpx;
					color: #979797;
					font-size: 28rpx;
					line-height: 40rpx;
					gap: 16rpx;
				}
			}

			.main-goods {
				margin-top: 32rpx;
				display: flex;
				flex-direction: column;
				row-gap: 32rpx;
			}

			.main-cost {
				margin-top: 32rpx;
				padding: 32rpx;
				border-radius: 16rpx;
				background: #FFFFFF;

				.cost-info {
					display: flex;
					justify-content: space-between;
					align-items: center;
					margin-top: 32rpx;

					&:first-child {
						margin-top: 0;
					}

					.title {
						color: #979797;
						font-size: 28rpx;
						line-height: 40rpx;
					}

					.value {
						color: var(--theme-color);
						font-size: 28rpx;
						line-height: 40rpx;
						margin-left: 24rpx;
					}
				}
			}

			.main-footer {
				position: fixed;
				left: 0;
				right: 0;
				bottom: 0;
				z-index: 96;
				background: #FFF;
				border-top: 1rpx solid #F6F7FB;
				padding: 16rpx 24rpx;

				.footer-money {
					color: var(--theme-color);
					font-size: 40rpx;
					line-height: 56rpx;
					word-break: break-all;

					text {
						font-size: 28rpx;
					}
				}

				.footer-btn {
					margin-left: 24rpx;
					padding: 20rpx 44rpx;
					background: var(--theme-color);
					border-radius: 16rpx;
					color: #FFF;
					text-align: center;
					font-size: 28rpx;
					line-height: 40rpx;
					min-width: 220rpx;
				}
			}
		}
	}
</style>